package com.yozinga.service;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.EventListener;

import javax.net.ssl.HttpsURLConnection;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.util.Log;

import com.yozinga.BaseActivity;
import com.yozinga.util.AlertDialogManager;
import com.yozinga.util.ToolKit;

public class ServiceHelper {

	private Handler mHandler = new Handler();
	Context mContext;
	EvalReceiver mEvalReceiver = new EvalReceiver(mHandler);
	private ArrayList<OnRequestFinishedListener> mListenerList;
	private static ServiceHelper serviceHelper;

	public ServiceHelper(Context context) {
		this.mContext = context;
		mListenerList = new ArrayList<OnRequestFinishedListener>();
	}

	public static ServiceHelper getInstance(Context context) {
		if (serviceHelper == null)
			serviceHelper = new ServiceHelper(context);
		// to update the context each time a service helper it's called
		serviceHelper.setContext(context);
		return serviceHelper;
	}

	private void setContext(Context context) {
		this.mContext = context;
	}

	/**
	 * Clients may implements this interface to be notified when a request is finished
	 */
	public static interface OnRequestFinishedListener extends EventListener {

		/**
		 * Event fired when a request is finished.
		 * 
		 * @param requestId
		 *            The request Id (to see if this is the right request)
		 * @param resultCode
		 *            The result code (0 if there was no error)
		 * @param payload
		 *            The result of the service execution.
		 */
		public void onRequestFinished(/*int requestId,*/ int resultCode, Bundle payload/*, RestActions action*/);
	}


	/** The ResultReceiver that will receive the result from the Service */
	private class EvalReceiver extends ResultReceiver {
		EvalReceiver(final Handler h) {
			super(h);
		}

		@Override
		public void onReceiveResult(final int resultCode, final Bundle resultData) {
			handleResult(resultCode, resultData);
		}
	}
	private void handleResult(int resultCode, Bundle resultData) {

		// Get the request Id
		switch(resultCode) {
		case HttpURLConnection.HTTP_OK:
			ProcessResponse(resultData);
			break;
		case HttpURLConnection.HTTP_UNAVAILABLE:
			// TODO: Broadcast or let it go?
			//AppData.DownTime = true;
			break;											
		case HttpsURLConnection.HTTP_MOVED_PERM:
		case HttpsURLConnection.HTTP_MOVED_TEMP:
		case HttpsURLConnection.HTTP_NOT_MODIFIED:
		case HttpsURLConnection.HTTP_BAD_REQUEST:
		case HttpsURLConnection.HTTP_NOT_FOUND:
		default:
			// TODO: Broadcast or let it go?
			break;
		}			

		// Call the available listeners
		synchronized (mListenerList) {
			for (int i = 0; i < mListenerList.size(); i++) {
				final OnRequestFinishedListener listener = mListenerList.get(i);
				if (listener != null && resultCode == HttpURLConnection.HTTP_OK || resultCode == 201 || resultCode == 204) {
					Log.i("Today","Resulet Code is:"+resultCode);
					listener.onRequestFinished(resultCode, resultData);
				} else {
					mListenerList.remove(i);
					i--;
				}
			}
		}

	}

	private void ProcessResponse(Bundle resultData) {

	}

	public void startService(/*String action, */String url,String id,int method,Bundle extras,String action) {

		if (ToolKit.isInternetAvailable(mContext)) {
			if(mContext!=null){
				final Intent intent = new Intent(mContext, YozingaService.class);
				intent.putExtra("url", url);
				intent.putExtra("id", id);
				intent.putExtra("method",method);
				intent.putExtra("action", action);
				if (extras != null) {
					Log.i("Today","extras != null");
					intent.putExtras(extras);
				}
				intent.putExtra(YozingaService.INTENT_EXTRA_RECEIVER, mEvalReceiver);
				mContext.startService(intent);
			}
		}else{
			ToolKit.stopprogess();
			AlertDialogManager alertDialogManager = new AlertDialogManager();
			alertDialogManager.showAlertDialog(mContext, "Network Failure", "You do not have internet access.  Please reconnect to the internet.", false, "OK");
			
		}
	}

	/**
	 * Add a {@link OnRequestFinishedListener} to this {@link PoCRequestManager} . Clients may use it in order to listen to events fired when a request is finished.
	 * <p>
	 * <b>Warning !! </b> If it's an {@link Activity} that is used as a Listener, it must be detached when {@link Activity#onPause} is called in an {@link Activity}.
	 * </p>
	 * 
	 * @param listener
	 *            The listener to add to this {@link PoCRequestManager} .
	 */
	public void addOnRequestFinishedListener(final OnRequestFinishedListener listener) {
		synchronized (mListenerList) {
			// Check if the listener is not already in the list
			if (!mListenerList.isEmpty()) {
				for (OnRequestFinishedListener listenerFromList : mListenerList) {
					if (listenerFromList.equals(null)) {
						continue;
					} else if (listenerFromList.equals(listener)) {
						return;
					}
				}
			}

			mListenerList.add(listener);
		}
	}

	/**
	 * Remove a {@link OnRequestFinishedListener} to this {@link PoCRequestManager}.
	 * 
	 * @param listenerThe
	 *            listener to remove to this {@link PoCRequestManager}.
	 */
	public void removeOnRequestFinishedListener(final OnRequestFinishedListener listener) {
		synchronized (mListenerList) {
			final int listenerListSize = mListenerList.size();
			for (int i = 0; i < listenerListSize; i++) {
				if (mListenerList.get(i).equals(listener)) {
					mListenerList.remove(i);
					return;
				}
			}
		}
	}
}
